package com.brsya.movie.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;


import com.brsya.base.util.UiUtil;
import com.brsya.movie.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Brsya
 * CreateDate: 2022/5/9  2:57
 * Description:
 * 评分View
 */
public class ScoreView extends LinearLayout {
    private List<View> scoreList;
    private TextView textView;

    private final int scoreColor = 0xFFFFDE24;
    private final int noColor = 0xFFAAAAAA;

    public ScoreView(Context context) {
        super(context);
        initView();
    }

    public ScoreView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public ScoreView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    private void initView() {
        setOrientation(HORIZONTAL);
        setGravity(Gravity.CENTER_VERTICAL);
        scoreList = new ArrayList<>();
        int dp10 = UiUtil.dpToPx(getContext(), 11);
        for (int i = 0; i < 5; i++) {
            View view = new View(getContext());
            LayoutParams layoutParams = new LayoutParams(dp10, dp10);
            layoutParams.rightMargin = UiUtil.dpToPx(getContext(), 4);
            view.setLayoutParams(layoutParams);
            addView(view);
            scoreList.add(view);
        }

        textView = new AppCompatTextView(getContext());
        textView.setTextSize(12);
        textView.setTextColor(scoreColor);
        LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        textView.setLayoutParams(layoutParams);
        addView(textView);

    }


    public void setScore(String score) {
        double scoreNumber;
        try {
            scoreNumber = Double.parseDouble(score);
        } catch (NumberFormatException exception) {
            //            scoreNumber = 0;
            for (View view : scoreList) {
                view.setVisibility(GONE);
            }
            textView.setText("暂无评分");
            textView.setTextColor(noColor);
            return;
        }

        textView.setText(score);
        textView.setTextColor(scoreColor);
        for (int i = 0; i < scoreList.size(); i++) {
            View view = scoreList.get(i);
            view.setVisibility(VISIBLE);
            if (scoreNumber <= 0) {
                view.setBackground(null);
            } else if (scoreNumber >= 2) {
                view.setBackgroundResource(R.mipmap.icon_score_all);
            } else {
                view.setBackgroundResource(R.mipmap.icon_score_half);
            }
            scoreNumber -= 2;
        }
    }


}
